<template>
  <div class="container" style="width: 100%; height: 80vh; overflow-y: auto;" v-loading="loading">
    <!-- 添加BUG弹窗 -->
    <!-- 编辑bug区域 -->
    <el-form class="dialog-form-box" ref="addBugFormRef" :model="addBugData" :rules="addBugRules">
      <!-- 标题 -->
      <el-form-item class="dialog-form-item-box" prop="bugTitle" style="width: 60%;">
        <div>
          <el-icon class="dialog-form-item-icon" :size="20">
            <CollectionTag />
          </el-icon>
        </div>
        <div class="dialog-title"><span style="color: red;">&ast;&nbsp;</span>标题：</div>
        <el-input style="width: 400px;" size="defalut" placeholder="请输入发现的bug现象" v-model="addBugData.bugTitle">
        </el-input>
      </el-form-item>

      <!-- 修复人 -->
      <el-form-item class="dialog-form-item-box" prop="editUserIds" style="width: 40%">
        <div>
          <el-icon class="dialog-form-item-icon" :size="20">
            <User />
          </el-icon>
        </div>
        <div class="dialog-title"><span style="color: red;">&ast;&nbsp;</span>修复人：</div>
        <div>
          <el-select v-model="addBugData.editUserIds" filterable multiple clearable collapse-tags collapse-tags-tooltip
            :max-collapse-tags="2" placeholder="请选择修复人员" style="width: 260px; font-size: 10px;">
            <el-option v-for="(item, index) in allCaseAvater" :key="index" :label="item.nickName" :value="item.uuid" />
          </el-select>
        </div>
      </el-form-item>

      <!-- bug等级 -->
      <el-form-item class="dialog-form-item-box" prop="bugLevel" style="width: 100%;">
        <div>
          <el-icon class="dialog-form-item-icon" :size="20">
            <EditPen />
          </el-icon>
        </div>
        <div class="dialog-title">&nbsp;&nbsp;BUG等级：</div>
        <el-radio-group v-model="addBugData.bugLevel" size="defalut">
          <el-radio-button label="致命" :value="1" class="bug-level-0" />
          <el-radio-button label="严重" :value="2" class="bug-level-1" />
          <el-radio-button label="一般" :value="3" class="bug-level-2" />
          <el-radio-button label="建议" :value="4" class="bug-level-3" />
        </el-radio-group>
      </el-form-item>

      <!-- 编辑bug -->
      <!-- <el-form-item prop="bug_msgs" style="width: 100%;">
        <div class="bug-edit-box" style="width: 960px;height: 380px;">
          <AddBugMsgVue v-model="addBugData.bug_msgs[0].bug_msg" @update:modelValue="updateModelValue" />
        </div>
      </el-form-item> -->

      <!-- bug详情录入 -->
      <div class="space-y-4">
        <el-form-item label="问题现象" prop="bugPhenomenon">
          <RichTextEditor2 v-model="addBugData.bugPhenomenon" @update:model-value="updateModelValue1"
            field-name="phenomenon1" />
        </el-form-item>

        <el-form-item label="复现步骤" prop="repeatSteps">
          <RichTextEditor3 v-model="addBugData.repeatSteps" @update:model-value="updateModelValue2"
            field-name="phenomenon2" />
        </el-form-item>

        <el-form-item label="影响范围" prop="scope">
          <el-input v-model="addBugData.scope" type="textarea" :rows="3" placeholder="如：影响系统使用" />
        </el-form-item>

        <el-form-item label="期望结果" prop="hopeResult">
          <el-input v-model="addBugData.hopeResult" type="textarea" :rows="3" placeholder="如：可以正常打开页面" />
        </el-form-item>
      </div>

      <!-- 底部添加/取消按钮 -->
      <el-form-item style="width: 100%;">
        <div class="bug-edit-btn">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAddBugData(addBugFormRef)">
            提交
          </el-button>
        </div>
      </el-form-item>
    </el-form>

  </div>
</template>

<script setup lang='ts'>
import AddBugMsgVue from './addBugMsg.vue';
import { ref, reactive, PropType, watch, onMounted } from 'vue';
import { ElMessage, FormInstance } from "element-plus";
import { isValidateEditor } from "@/utils/utils"; //引入公共函数
import { addRequirementBug } from "@/api/bug/index"; // 引入接口函数
import useCommonDataStore from "@/store/common/common"; //获取所有的修复人
import { PostAddNewRequirementBug } from "@/api/newDemands/index";
import RichTextEditor2 from '@/views/experiment/bugs/editor2.vue'
import RichTextEditor3 from '@/views/experiment/bugs/editor3.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  id: {
    type: Number as PropType<number | null>,
    required: true
  }
});



const loading = ref(false);
let allRoleUsersStore = useCommonDataStore();
// 定义所有修复人员姓名和头像
const allCaseAvater = ref<any>([]);
// 定义添加bug弹窗控件
// const dialogAddBugVisible = ref(false);

// 定义添加bug表单实例
const addBugFormRef = ref<FormInstance>();
// 定义添加bug表单验证规则
const addBugRules = reactive({
  bugTitle: [
    {
      required: true,
      message: "请输入bug名称",
      trigger: "blur",
    },
  ],
  editUserIds: [{
    required: true,
    message: "请选择修复人员",
    trigger: "blur",
  }],
  bugPhenomenon: [{
    required: true,
    trigger: "blur",
    validator: (rule: any, value: any, callBack: any) => {
      if ((isValidateEditor(value))) {
        callBack(new Error('不能为空格或空行'));
      } else {
        callBack();
      }
    },
  }],
  repeatSteps: [{
    required: true,
    trigger: "blur",
    validator: (rule: any, value: any, callBack: any) => {
      if ((isValidateEditor(value))) {
        callBack(new Error('不能为空格或空行'));
      } else {
        callBack();
      }
    },
  }],
  scope: [{
    required: true,
    trigger: "blur",
    validator: (rule: any, value: any, callBack: any) => {
      if ((isValidateEditor(value))) {
        callBack(new Error('不能为空格或空行'));
      } else {
        callBack();
      }
    },
  }],
  hopeResult: [{
    required: true,
    trigger: "blur",
    validator: (rule: any, value: any, callBack: any) => {
      if ((isValidateEditor(value))) {
        callBack(new Error('不能为空格或空行'));
      } else {
        callBack();
      }
    },
  }],
  /*  bug_msgs: [{
     validator: (rule: any, value: any, callBack: any) => {
       if ((isValidateEditor(value[0].bug_msg))) {
         // alert(`"富文本校验结果：",${isValidateEditor(value[0].bug_msg)}`);
         callBack(new Error('BUG详情不能为空'));
       } else {
         callBack();
       }
     },
     required: true,
     trigger: "blur",
   }] */
});
// 初始化-添加bug弹窗
// const initAddBug = () => ({
//   itemRequirementId: null as any,
//   bugTitle: "",
//   bugLevel: 2,
//   editUserIds: [] as Array<any>,
//     bugStatus: 0,
//     bug_msgs: [
//       { bug_msg: "" }
//     ]
//   });
const initAddBug = () => ({
  itemRequirementId: null as any,
  bugTitle: "",
  bugLevel: 3,
  editUserIds: [] as Array<any>,
  bugStatus: 0,
  bugPhenomenon: "",
  repeatSteps: "",
  scope: "",
  hopeResult: ""
});
// 定义添加bug请求参数初始值
const addBugData = reactive(initAddBug());


const emit = defineEmits(['submit-success']);

// 监听 id 的变化，获取数据
watch(() => props.id, async (newId) => {
  if (newId) {
    initAddBug();
    addBugFormRef.value?.resetFields();
    addBugData.itemRequirementId = newId;
  }
}, { immediate: true });

// TODO 获取初始数据
const getInitData = async () => {
  allCaseAvater.value = await allRoleUsersStore.getAllRoleUsersList("");
  addBugData.itemRequirementId = props.id;
};


// TODO 取消添加bug
const handleCancel = () => {
  addBugData.bugLevel = 3;
  addBugData.itemRequirementId = null;
  addBugData.bugTitle = "";
  // addBugData.bug_msgs[0].bug_msg = "";
  addBugData.bugStatus = 0;
  addBugData.editUserIds = [];
  addBugData.bugPhenomenon = "";
  addBugData.repeatSteps = "";
  addBugData.scope = "";
  addBugData.hopeResult = "";

  emit('submit-success', false);
};


// 富文本数据更新
const updateModelValue1 = (newValue: any) => {
  addBugData.bugPhenomenon = newValue;
  return addBugData.bugPhenomenon;
};
const updateModelValue2 = (newValue: any) => {
  addBugData.repeatSteps = newValue;
  return addBugData.repeatSteps;
};


// TODO 提交添加bug
const handleAddBugData = async (formEl: FormInstance | undefined) => {
  loading.value = true;

  // 监听富文本内容
  window.addEventListener("update:modelValue", updateModelValue1);
  window.addEventListener("update:modelValue", updateModelValue2);

  if (!formEl) {
    console.error("表单验证失败，请将内容填写完整");
    return;
  };

  // 表单验证
  const validatePromise = formEl.validate();
  try {
    await validatePromise;
    // 表单验证成功
    addBugData.bugPhenomenon = addBugData.bugPhenomenon.trim();
    addBugData.repeatSteps = addBugData.repeatSteps.trim();
    addBugData.scope = addBugData.scope.trim();
    addBugData.hopeResult = addBugData.hopeResult.trim();

    // 发起请求
    // const { data } = await addRequirementBug(addBugData);
    const { data } = await PostAddNewRequirementBug(addBugData);
    if (data.code === 200) {
      // ElMessage.success(data.msg);
      initAddBug();
      emit('submit-success', true);
      loading.value = false;
    } else {
      // ElMessage.error(data.msg);
      initAddBug();
      emit('submit-success', false);
      loading.value = false;
      throw console.error(data.msg);
    }
  } catch (error) {
    // 表单验证失败
    loading.value = false;
    console.error("表单验证失败，请将内容填写完整");
    return;
  }
};

onMounted(() => {
  getInitData();
})
</script>
<style lang='scss' scoped>
.container {
  width: 100%;

  // TODO 添加bug弹窗
  .dialog-form-box {
    width: 100%;
    // height: 720px;
    // padding: 20px;
    // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    .dialog-form-item-icon svg {
      margin-top: 15px;
    }

    .dialog-form-item-box {
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;


      // bug等级按钮
      .bug-level-0 {
        --el-radio-button-checked-bg-color: #B40404;
        --el-radio-button-checked-border-color: #B40404;
        list-style: none;
        border: 1px solid #dcdcdc;
        border-radius: 5px 0 0 5px;
      }

      .bug-level-1 {
        list-style: none;
        border: 1px solid #dcdcdc;
        --el-radio-button-checked-bg-color: #ff0000;
        --el-radio-button-checked-border-color: #ff0000;
      }

      .bug-level-2 {
        list-style: none;
        border: 1px solid #dcdcdc;
        --el-radio-button-checked-bg-color: #67c23a;
        --el-radio-button-checked-border-color: #67c23a;
      }

      .bug-level-3 {
        list-style: none;
        border: 1px solid #dcdcdc;
        border-radius: 0 5px 5px 0;
      }

      // bug编辑区域
      .bug-edit-box {
        width: 900px;
        height: 510px;
        border-top: 1px solid #ddd;
        box-shadow: none;
        border-radius: 0;
        padding: 10px 20px;
      }
    }

    // 添加bug操作区域
    .bug-edit-btn {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      margin-right: 20px;
      padding-top: 40px;
    }
  }
}

;
</style>
